from time import gmtime, strftime, strptime
from datetime import date, timedelta
import time, Xml, os, InterfaceRB, InterfaceExt

def checkMonthBoundaries(monthNumber, yearNumber=time.strftime("%Y")):
    """Used to retrieve the correct amount of files within a given month"""
    
    listFiles=[]
    boundaries=[]
    list = Xml.retrieveInfoXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml', 'BackupDir')
    listBackup=os.listdir(list[0])
    boundaryBegin='01-'+monthNumber+'-'+yearNumber
    boundary=get_last_day(date(int(yearNumber),int(monthNumber), 15))
    a = strptime(str(boundary), "%Y-%m-%d")
    boundaryEnd= strftime("%d-%m-%Y", a)
    boundaries.append(boundaryBegin)
    boundaries.append(boundaryEnd)
    return boundaries

def get_first_day(dt, d_years=0, d_months=0):
    """Retrieve first day of the month"""
    
    y, m = dt.year + d_years, dt.month + d_months
    a, m = divmod(m-1, 12)
    return date(y+a, m+1, 1)

def get_last_day(dt):
    """Retrieve last day of the month"""
    
    return get_first_day(dt, 0, 1) + timedelta(-1)

def ExcludeCleanup(boundaryEnd):
    """Check last backup for each file and launch cleanup if safe"""
    
    list = Xml.retrieveAllXml('C:\\Program Files\\EasyBackupTool\\BackupTimes.xml')
    listOfCleanup = []
    for element in list:
        splitUnderscore = element.split('_')
        splitAt = splitUnderscore[-1].split('@')
        lastBackupDate = strptime(splitAt[0], "%d-%m-%Y")
        #print lastBackupDate
        #print strptime(boundaryEnd, "%d-%m-%Y")
        if lastBackupDate > strptime(boundaryEnd, "%d-%m-%Y"):
            # safe to cleanup
            listOfCleanup.append(splitUnderscore[0]) 
    return listOfCleanup

def Clean(listValid, boundaryBegin, boundaryEnd):
    """Delete All of month but last"""

    list = Xml.retrieveInfoXml('C:\\Documents and Settings\\All Users\\Application Data\\EBT\\EBT-setup.xml', 'BackupDir')
    listBackup=os.listdir(list[0])
    
    bool=False
    
    listCleanup = []
    for element in listBackup:
        splitExtention =  element.split('.')
        if splitExtention[-1] == 'acl' or splitExtention[-1] == 'xdelta':
            # take care of not taking initial file
            splitUnderscore = element.split('_')
            if splitUnderscore[0] in listValid:
                #take care of taking only safe files to delete (Safe = not most recent backup file)
                splitAt = splitUnderscore[-1].split('@')
                lastBackupDate = strptime(splitAt[0], "%d-%m-%Y")
                if (lastBackupDate > strptime(boundaryBegin, "%d-%m-%Y")) and (lastBackupDate < strptime(boundaryEnd, "%d-%m-%Y")) :
                    #check that the file we will delete are set to be higher than the minimal boundary
                    listCleanup.append(element)
    
    for elements in listValid:
        latestOfMonthDelta = InterfaceRB.getClosestAclDate(elements, boundaryEnd+'@23h59m59s', 'xdelta')
        latestOfMonthACL = InterfaceRB.getClosestAclDate(elements, latestOfMonthDelta)
        if latestOfMonthDelta != '01-01-1901@01h01m01s':
            reconstructDelta = elements + '_' + latestOfMonthDelta + '.xdelta'
            reconstructACL = elements + '_' + latestOfMonthACL + '.acl'
            if reconstructDelta in listCleanup:
                listCleanup.remove(reconstructDelta)
            if reconstructACL in listCleanup:
                listCleanup.remove(reconstructACL)
        else:
            bool=True
            for elem in listCleanup:
                listCleanup.remove(elem)
    
    if bool==True:
        print 'Impossible - Cleanup has already been done, or not possible yet'
    else:
        InterfaceExt.deleteFileH(listCleanup)
#    print listCleanup     
         

def MonthlyCleanup(monthNumber, yearNumber=time.strftime("%Y")):
    bound = checkMonthBoundaries(monthNumber, yearNumber)
    print bound
    res = ExcludeCleanup(bound[-1])
    print res
    Clean(res, bound[0], bound[-1])

if __name__ == "__main__":
    print time.strftime("%m-%Y")
    #print get_last_day(date(2006, 2, 15))
    #checkMonthBoundaries('02', '2007')
    #checkMonthBoundaries('07')
    #MonthlyCleanup('07','2008')
    #Clean(get, '01-06-2008', '30-06-2008')
    